package org.hiberlyzer.ui;

import java.awt.Frame;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

import org.hiberlyzer.Metadata;
import org.hiberlyzer.MetadataSource;
import org.hiberlyzer.Property;

public class CollectionDetailDialog extends JDialog
{
	public CollectionDetailDialog(Collection collection, Frame owner, MetadataSource metadataSource)
	{
		super(owner, "Collection details");
		JTable table = new JTable();
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // without this, columns will be smashed to fit window
		for(Iterator iter = collection.iterator(); iter.hasNext();)
		{
			Object collectionItem = iter.next();
			if(collectionItem != null)
			{
				Metadata objectMetadata = metadataSource.getObjectMetadata(collectionItem);
				table.setModel(getModel(collection, objectMetadata));
				break;
			}
		}
		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane);
		pack();
	}
	
	private TableModel getModel(Collection collection, Metadata metadata)
	{
		final List list = new ArrayList(collection);
		final List<Property> columns = new ArrayList<Property>(metadata.getProperties());
		columns.add(0, metadata.getIdentifier());
		
		return new AbstractTableModel(){

			public int getColumnCount()
			{
				return columns.size();
			}

			@Override
			public String getColumnName(int column)
			{
				return columns.get(column).getName();
			}

			public int getRowCount()
			{
				return list.size();
			}

			public Object getValueAt(int rowIndex, int columnIndex)
			{
				return columns.get(columnIndex).getValue(list.get(rowIndex));
			}};
	}
}
